﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web;
using System.Collections.Generic;


/// <summary>
/// Descripción breve de Machine
/// </summary>
public class Machine
{
    private int _Pk_Machine;   
    private string _Machine_Name;    
    private string _Machine_Acron;
    private string _Machine_AcronNumber;
    public int Id_IPDB = -1;

    public string Machine_AcronNumber
    {
        get { return _Machine_AcronNumber; }
        set { _Machine_AcronNumber = value; }
    }
    private byte _Machine_Number;  

    public int Pk_Machine
    {
        get { return _Pk_Machine; }
        set { _Pk_Machine = value; }
    }
    public string Machine_Name
    {
        get { return _Machine_Name; }
        set { _Machine_Name = value; }
    }
    public string Machine_Acron
    {
        get { return _Machine_Acron; }
        set { _Machine_Acron = value; }
    }
    public byte Machine_Number
    {
        get { return _Machine_Number; }
        set { _Machine_Number = value; }
    }

	public Machine()
	{		
	}

    public Machine(int p_Pk_Machine,string p_Machine_Name,
                   string p_Machine_Acron, byte p_Machine_Number) {
           
           this._Pk_Machine = p_Pk_Machine;
           this._Machine_Name = p_Machine_Name;
           this._Machine_Acron = p_Machine_Acron;
           this._Machine_Number = p_Machine_Number;
           this._Machine_AcronNumber = p_Machine_Number.ToString() + " (" + p_Machine_Acron + ")";

    }

    public Machine(int p_Pk_Machine)
    {
        try
        {
            DataTable oDataTable = DataBase.dt("SELECT Pk_Machine,Machine_Name,Machine_Acron,Machine_Number FROM Machines WHERE Pk_Machine =" + p_Pk_Machine.ToString());

            if(oDataTable.Rows.Count > 0) {
                this._Pk_Machine = Int32.Parse(oDataTable.Rows[0]["Pk_Machine"].ToString());
                this._Machine_Number = Byte.Parse(oDataTable.Rows[0]["Machine_Number"].ToString());
                this._Machine_Acron = oDataTable.Rows[0]["Machine_Acron"].ToString();
                this._Machine_Name = oDataTable.Rows[0]["Machine_Name"].ToString();
            }                
        }
        catch (Exception Ex)
        {
            throw;
        }
    }

    public Machine(string p_Machine_Name,
             string p_Machine_Acron, byte p_Machine_Number)
    {

        this._Machine_Name = p_Machine_Name;
        this._Machine_Acron = p_Machine_Acron;
        this._Machine_Number = p_Machine_Number;
        this._Machine_AcronNumber = p_Machine_Number.ToString() + "(" + p_Machine_Acron + ")";

    }

    public static Machine GetMachineByMachineNumber(int p_MachineNumber,int p_Tournament)
    {
        Machine oMachine= new Machine();
        try
        {
            //DataTable oDataTable = DataBase.dt("SELECT Pk_Machine,Machine_Name,Machine_Acron,Machine_Number FROM Machines M  WHERE M.Machine_Number=" + p_MachineNumber.ToString() + "AND M.");
            DataTable oDataTable = DataBase.dt("SELECT Pk_Machine,Machine_Name,Machine_Acron,Machine_Number FROM Machines M INNER JOIN MachinesTournament MT ON MT.Fk_Machine = M.Pk_Machine WHERE MT.Fk_Tournament=" + p_Tournament + " AND M.Machine_Number=" + p_MachineNumber.ToString());

            //List<Machine> ReturnList = new List<Machine>();
            
            foreach (DataRow iRow in oDataTable.Rows)
            {
                oMachine = new Machine(Int32.Parse(iRow["Pk_Machine"].ToString()), iRow["Machine_Name"].ToString(), iRow["Machine_Acron"].ToString(), Byte.Parse(iRow["Machine_Number"].ToString()));
                
            }
            return oMachine;
        }
        catch (Exception Ex)
        {
            throw;
        }

    }

    public static int InsertMachine(Machine p_Machine,int p_Pk_Tournament){
        OleDbConnection objConnection = new OleDbConnection();
        try
        {
            objConnection = DataBase.GetConnection();
            
            OleDbCommand objCommand = new OleDbCommand("INSERT INTO Machines (Machine_Name,Machine_Acron,Machine_Number,IdIPDB) VALUES ('" + p_Machine._Machine_Name.ToString() + "','" + p_Machine._Machine_Acron.ToString() + "'," + p_Machine._Machine_Number.ToString() + "," + p_Machine.Id_IPDB.ToString() + ")", objConnection);
            objConnection.Open();
            objCommand.ExecuteNonQuery();

            OleDbCommand cmdGetIdentity = new OleDbCommand();
            cmdGetIdentity.CommandText = "SELECT @@IDENTITY";
            cmdGetIdentity.Connection = objConnection;

            int Identity = Int32.Parse(cmdGetIdentity.ExecuteScalar().ToString());

            //Insertamos la relación con el torneo            
            objCommand = new OleDbCommand("INSERT INTO MachinesTournament (Fk_Machine,Fk_Tournament) VALUES (" + Identity.ToString() + "," + p_Pk_Tournament.ToString() + ")", objConnection);           
            objCommand.ExecuteNonQuery();

            return Identity;


        }
        catch (Exception Ex)
        {
            throw Ex;
        }
        finally
        {
            objConnection.Close();
        } 
    }

    public static List<Machine> GetMachinesByTournament(int p_Pk_Tournament) {
        try
        {
            Tournament oTour = new Tournament(p_Pk_Tournament);
            DataTable oDataTable;
            if (oTour.TournamentType == 0)
            {
                oDataTable = DataBase.dt("SELECT Pk_Machine,Machine_Name,Machine_Acron,Machine_Number FROM Machines M INNER JOIN MachinesTournament MT ON MT.Fk_Machine = M.Pk_Machine WHERE MT.Fk_Tournament=" + p_Pk_Tournament);
            }
            else {
                //Oder by number not by rounds
                oDataTable = DataBase.dt("SELECT Pk_Machine,Machine_Name,Machine_Acron,Machine_Number FROM Machines M INNER JOIN MachinesTournament MT ON MT.Fk_Machine = M.Pk_Machine WHERE MT.Fk_Tournament=" + p_Pk_Tournament + " order by Machine_Number");
            }

            List<Machine> ReturnList = new List<Machine>();

            foreach (DataRow iRow in oDataTable.Rows)
            {
                Machine oMachine = new Machine(Int32.Parse(iRow["Pk_Machine"].ToString()), iRow["Machine_Name"].ToString(), iRow["Machine_Acron"].ToString(), Byte.Parse(iRow["Machine_Number"].ToString()));
                ReturnList.Add(oMachine);
            }
            return ReturnList;
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

    public static List<Machine> GetQualifyMachinesByPlayer(int p_Pk_Player, int p_Pk_Tournament)
    {
        try
        {
            Tournament oTour = new Tournament(p_Pk_Tournament);
            DataTable oDataTable;
            if (oTour.TournamentType == 0)
            {
                oDataTable = DataBase.dt("SELECT Pk_Tournament,Fk_Machine,Round_Number,Fk_Player,MachineScore,Is_Joker,PlayInPosition,Player_Nick,Fk_Player_Zone,Machine_Acron,PlayerNumber,Machine_Number FROM QualifyTournamentRounds WHERE Pk_Tournament=" + p_Pk_Tournament.ToString() + " and Fk_Player=" + p_Pk_Player.ToString());
            }
            else {
                oDataTable = DataBase.dt("SELECT Pk_Tournament,Fk_Machine,Round_Number,Fk_Player,MachineScore,Is_Joker,PlayInPosition,Player_Nick,Fk_Player_Zone,Machine_Acron,PlayerNumber,Machine_Number FROM QualifyTournamentRounds WHERE Pk_Tournament=" + p_Pk_Tournament.ToString() + " and Fk_Player=" + p_Pk_Player.ToString() + " order by Machine_Number");            
            }
            List<Machine> ReturnList = new List<Machine>();
            foreach (DataRow iRow in oDataTable.Rows)
            {
                QualifyRound oQualifyRound = new QualifyRound(Int32.Parse(iRow["Pk_Tournament"].ToString()),
                                                              Int32.Parse(iRow["Fk_Player"].ToString()),
                                                              iRow["Player_Nick"].ToString(),
                                                              Int32.Parse(iRow["Round_Number"].ToString()),
                                                              Int32.Parse(iRow["Fk_Player_Zone"].ToString()),
                                                              Int32.Parse(iRow["Fk_Machine"].ToString()),
                                                              iRow["Machine_Acron"].ToString(),
                                                              Int32.Parse(iRow["Machine_Number"].ToString()),
                                                              Int32.Parse(iRow["PlayInPosition"].ToString()),
                                                              Int64.Parse(iRow["MachineScore"].ToString()),
                                                              Int32.Parse(iRow["PlayerNumber"].ToString()),
                                                              Boolean.Parse(iRow["Is_Joker"].ToString()));

                Machine oMachine = new Machine(Int32.Parse(iRow["Fk_Machine"].ToString()), "", iRow["Machine_Acron"].ToString(), Byte.Parse(iRow["Machine_Number"].ToString()));
                ReturnList.Add(oMachine);


            }
            
            return ReturnList;
        }
        catch (Exception Ex)
        {
            throw;
        }
    }


    public static Boolean DeleteMachine(int Pk_Machine){
     OleDbConnection objConnection = new OleDbConnection();
        try
        {
            //TODO controlar si hay un playerNumber duplicado
            objConnection = DataBase.GetConnection();
            OleDbCommand objCommand = new OleDbCommand("DELETE * FROM MachinesTournament WHERE Fk_Machine=" + Pk_Machine.ToString(), objConnection);
            objConnection.Open();
            objCommand.ExecuteNonQuery();

            objCommand = new OleDbCommand("DELETE * FROM Machines WHERE Pk_Machine=" + Pk_Machine.ToString(), objConnection);
            objCommand.ExecuteNonQuery();

            return true;


        }
        catch (Exception Ex)
        {
            return false;
        }
        finally
        {
            objConnection.Close();
        }
    }
}
